#include "Plane.h"

float int_sgn(float t) {
    return (0 < t) - (t < 0);
}

/* only call this if check_collide returns true */
glm::vec3 Plane::collide(glm::vec3 prev, glm::vec3 pos) {
    glm::vec3 d;
    glm::vec3 pointOnPlane;
    float t;
    
    d = (pos - prev);

    if (normal.z != 0) 
        pointOnPlane = glm::vec3(0.f, 0.f, -distance / normal.z);
    else if (normal.y != 0) 
        pointOnPlane = glm::vec3(0.f, -distance / normal.y, 0.f);
    else if (normal.x != 0) 
        pointOnPlane = glm::vec3(-distance / normal.x, 0.f, 0.f);

    t = glm::dot(pointOnPlane - prev, normal) / glm::dot(d, normal);
    return prev + d * t - int_sgn(glm::dot(d, normal)) * normal * 0.01f;

}

bool Plane::check_collide(glm::vec3 prev, glm::vec3 pos) {
    /* we need to determine if the particle is on the same side of the 
     * plane as it started on
     *
     * Basically:
     *    sgn(pos) == sgn(prev) --> pos and prev are both on the same
     *      side of the plane
     *    sgn(pos) != sgn(prev) --> pos and prev are on oppositte sides
     */
    return sgn(pos) != sgn(prev);
}

int Plane::sgn(glm::vec3 pos) {
    return glm::dot(pos, normal) + distance <= 0;
}
